/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
    handler: (req, res, next)=>{
        const userId=req.context.user;
        const compress=req.query.compress;
        const gfs = Grid(req.mongo, mongo);

        var busboy = new Busboy({headers: req.headers});
        //第三方中间件接收上传
        var files = [];
        var fileCount = 0;
        req.pipe(busboy);
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            var ext = path.extname(filename).toLowerCase();
            fileCount = fileCount + 1;
            var filesize = 0;
            var id = new ObjectID();
            //console.log(file);

            var writestream = gfs.createWriteStream({
                _id: id,
                mode: "w",
                filename: filename,
                content_type: mimetype
            });
            if (mimetype.indexOf("image/") != -1&&compress=="true") {
                gm(file).resize('640', '480').stream().pipe(writestream);
            } else {
                file.pipe(writestream);
            }
            writestream.on('finish', function () {
                console.log("处理完成");
                const url = "http://" + req.headers.host + "/res/" + id+"/content";
                var fileObj = {
                    id: id,
                    filename: filename,
                    content_type: mimetype,
                    filesize: filesize,
                    url: url
                }
                files.push(fileObj);
                //将资源记录用户表
                var fn = function () {
                };
                req.mongo.collection("userMedia").insert({_id: userId}, function () {
                    if ([".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"].indexOf(ext)>=0) {
                        req.mongo.collection("userMedia").update({_id: userId}, {$push: {"videos": id}}, fn);
                    } else if ([".png", ".jpg", ".jpeg", ".gif", ".bmp"].indexOf(ext)>=0) {
                        req.mongo.collection("userMedia").update({_id: userId}, {$push: {"images": id}}, fn);
                    } else {
                        req.mongo.collection("userMedia").update({_id: userId}, {$push: {"files": id}}, fn);
                    }
                });
            })

            file.on('end', function () {
                console.log("上传结束");
            }).on('error', function (err) {
                next(err);
            }).on('data', function (data) {
                filesize += data.length;
                console.log(filesize);
            });

        }).on('error', function (err) {
            console.log("busboy error:" + err);
            next(err);
        });

        function checkExit() {
            var a = setTimeout(function () {
                if (files.length == fileCount) {
                    res.json(files);
                    clearTimeout(a);
                    clearTimeout(b);
                }
                console.log("files.length:%d,fileCount:%d", files.length, fileCount);
            }, 300);

            var b = setTimeout(checkExit, 300);
        }

        checkExit();
    }
};